package com.cat.bitOperation;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/minimize-xor/
 * @create 2025/8/20 14:47
 * @since JDK17
 */

public class Solution07 {
    public int minimizeXor(int num1, int num2) {
        int n1 = Integer.bitCount(num1), n2 = Integer.bitCount(num2);
        if (n1 == n2) {
            return num1;
        } else if (n1 > n2) {
            int cnt = n1 - n2;
            for (int i = 0; i < 32; i++) {
                if ((num1 & (1 << i)) != 0) {   //
                    num1 ^= 1 << i;
                    cnt--;
                }
                if (cnt == 0) {
                    return num1;
                }
            }
        } else {
            int cnt = n2 - n1;
            for (int i = 0; i < 32; i++) {
                if ((num1 & 1 << i) == 0) {
                    num1 |= 1 << i;
                    cnt--;
                }
                if (cnt == 0) {
                    return num1;
                }
            }
            return 0;
        }
        return -1;
    }
}
